import axios, { AxiosInstance, AxiosResponse } from 'axios';
import { message } from 'antd';
import {
  User,
  LoginRequest,
  RegisterRequest,
  AuthResponse,
  Product,
  ProductCategory,
  Portfolio,
  PortfolioHolding,
  Transaction,
  FundData,
  MarketData,
  AssetAllocation,
  AllocationResult,
  PaginatedResponse,
  ApiResponse
} from '../types';

// API基础配置
const API_BASE_URL = process.env.REACT_APP_API_URL || 'http://localhost:8000/api';

// 创建axios实例
const apiClient: AxiosInstance = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器 - 添加认证token
apiClient.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token') || '410584b2bee95a46af5bcfc5434c217576d50e35'; // 临时测试token
    if (token) {
      config.headers.Authorization = `Token ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器 - 处理错误
apiClient.interceptors.response.use(
  (response: AxiosResponse) => {
    return response;
  },
  (error) => {
    if (error.response) {
      const { status, data } = error.response;
      
      switch (status) {
        case 401:
          // 未授权，清除token并跳转到登录页
          localStorage.removeItem('token');
          localStorage.removeItem('user');
          window.location.href = '/login';
          message.error('登录已过期，请重新登录');
          break;
        case 403:
          message.error('没有权限访问此资源');
          break;
        case 404:
          message.error('请求的资源不存在');
          break;
        case 500:
          message.error('服务器内部错误');
          break;
        default:
          if (data?.message) {
            message.error(data.message);
          } else {
            message.error('请求失败，请稍后重试');
          }
      }
    } else if (error.request) {
      message.error('网络连接失败，请检查网络设置');
    } else {
      message.error('请求配置错误');
    }
    
    return Promise.reject(error);
  }
);

// 用户认证API
export const authAPI = {
  // 用户登录
  login: async (data: LoginRequest): Promise<AuthResponse> => {
    const response = await apiClient.post('/auth/login/', data);
    return response.data;
  },

  // 用户注册
  register: async (data: RegisterRequest): Promise<AuthResponse> => {
    const response = await apiClient.post('/auth/register/', data);
    return response.data;
  },

  // 用户登出
  logout: async (): Promise<void> => {
    await apiClient.post('/auth/logout/');
  },

  // 获取用户信息
  getProfile: async (): Promise<User> => {
    const response = await apiClient.get('/auth/profile/');
    return response.data;
  },

  // 更新用户信息
  updateProfile: async (data: Partial<User>): Promise<User> => {
    const response = await apiClient.put('/auth/profile/', data);
    return response.data;
  },

  // 修改密码
  changePassword: async (data: { old_password: string; new_password: string }): Promise<void> => {
    await apiClient.post('/auth/change-password/', data);
  },
};

// 产品API
export const productAPI = {
  // 获取产品分类
  getCategories: async (): Promise<ProductCategory[]> => {
    const response = await apiClient.get('/products/categories/');
    return response.data;
  },

  // 获取产品列表
  getProducts: async (params?: {
    category?: number;
    search?: string;
    risk_level?: number;
    page?: number;
    page_size?: number;
  }): Promise<PaginatedResponse<Product>> => {
    const response = await apiClient.get('/products/', { params });
    return response.data;
  },

  // 获取产品详情
  getProduct: async (id: number): Promise<Product> => {
    const response = await apiClient.get(`/products/${id}/`);
    return response.data;
  },

  // 搜索产品
  searchProducts: async (keyword: string): Promise<Product[]> => {
    const response = await apiClient.get('/products/search/', {
      params: { keyword }
    });
    return response.data;
  },

  // 获取产品推荐
  getRecommendations: async (risk_level: number): Promise<Product[]> => {
    const response = await apiClient.get('/products/recommendations/', {
      params: { risk_level }
    });
    return response.data;
  },
};

// 投资组合API
export const portfolioAPI = {
  // 获取投资组合列表
  getPortfolios: async (): Promise<Portfolio[]> => {
    const response = await apiClient.get('/portfolios/');
    // 处理分页响应格式
    if (response.data && response.data.results) {
      return response.data.results;
    }
    return Array.isArray(response.data) ? response.data : [];
  },

  // 创建投资组合
  createPortfolio: async (data: {
    name: string;
    description?: string;
    total_amount: number;
  }): Promise<Portfolio> => {
    const response = await apiClient.post('/portfolios/', data);
    return response.data;
  },

  // 获取投资组合详情
  getPortfolio: async (id: number): Promise<Portfolio> => {
    const response = await apiClient.get(`/portfolios/${id}/`);
    return response.data;
  },

  // 更新投资组合
  updatePortfolio: async (id: number, data: Partial<Portfolio>): Promise<Portfolio> => {
    const response = await apiClient.put(`/portfolios/${id}/`, data);
    return response.data;
  },

  // 删除投资组合
  deletePortfolio: async (id: number): Promise<void> => {
    await apiClient.delete(`/portfolios/${id}/`);
  },

  // 获取投资组合持仓
  getHoldings: async (portfolioId: number): Promise<PortfolioHolding[]> => {
    const response = await apiClient.get(`/portfolios/${portfolioId}/holdings/`);
    // 处理分页响应格式
    if (response.data && response.data.results) {
      return response.data.results;
    }
    return Array.isArray(response.data) ? response.data : [];
  },

  // 获取交易记录
  getTransactions: async (portfolioId: number): Promise<Transaction[]> => {
    const response = await apiClient.get(`/portfolios/${portfolioId}/transactions/`);
    // 处理分页响应格式
    if (response.data && response.data.results) {
      return response.data.results;
    }
    return Array.isArray(response.data) ? response.data : [];
  },

  // 创建交易
  createTransaction: async (portfolioId: number, data: {
    product: number;
    transaction_type: 'buy' | 'sell';
    quantity: number;
    price: number;
  }): Promise<Transaction> => {
    const response = await apiClient.post(`/portfolios/${portfolioId}/transactions/`, data);
    return response.data;
  },

  // 资产配置建议
  getAssetAllocation: async (data: AssetAllocation): Promise<AllocationResult> => {
    const response = await apiClient.post('/portfolios/asset-allocation/', data);
    return response.data;
  },

  // 投资组合再平衡
  rebalancePortfolio: async (portfolioId: number, rebalanceType: string): Promise<any> => {
    const response = await apiClient.post('/portfolios/rebalance/', {
      portfolio_id: portfolioId,
      rebalance_type: rebalanceType
    });
    return response.data;
  },

  // 获取投资组合业绩
  getPerformance: async (portfolioId: number, days?: number): Promise<any> => {
    const response = await apiClient.get(`/portfolios/${portfolioId}/performance/`, {
      params: { days }
    });
    return response.data;
  },

  // 获取风险分析
  getRiskAnalysis: async (portfolioId: number): Promise<any> => {
    const response = await apiClient.get(`/portfolios/${portfolioId}/risk-analysis/`);
    return response.data;
  },
};

// 数据服务API
export const dataAPI = {
  // 获取基金数据
  getFunds: async (params?: {
    search?: string;
    fund_type?: string;
    page?: number;
    page_size?: number;
  }): Promise<PaginatedResponse<FundData>> => {
    const response = await apiClient.get('/data/funds/', { params });
    return response.data;
  },

  // 获取基金详情
  getFund: async (fundCode: string): Promise<FundData> => {
    const response = await apiClient.get(`/data/funds/${fundCode}/`);
    return response.data;
  },

  // 搜索基金
  searchFunds: async (params: {
    keyword?: string;
    fund_type?: string;
    risk_level?: number;
    min_return?: number;
    max_return?: number;
  }): Promise<PaginatedResponse<FundData>> => {
    const response = await apiClient.get('/data/funds/search/', { params });
    return response.data;
  },

  // 获取基金业绩
  getFundPerformance: async (fundCode: string, days?: number): Promise<any> => {
    const response = await apiClient.get(`/data/funds/${fundCode}/performance/`, {
      params: { days }
    });
    return response.data;
  },

  // 获取市场数据
  getMarketData: async (params?: {
    indicator_type?: string;
    days?: number;
  }): Promise<MarketData[]> => {
    const response = await apiClient.get('/data/market/', { params });
    return response.data;
  },

  // 获取市场指标
  getMarketIndicators: async (): Promise<any> => {
    const response = await apiClient.get('/data/market/indicators/');
    return response.data;
  },

  // 获取基金统计信息
  getFundStatistics: async (): Promise<any> => {
    const response = await apiClient.get('/data/funds/statistics/');
    return response.data;
  },

  // 导出基金数据
  exportFundData: async (search?: string): Promise<Blob> => {
    const response = await apiClient.get('/data/funds/export/', {
      params: { search },
      responseType: 'blob'
    });
    return response.data;
  },

  // 创建数据同步任务
  createSyncTask: async (data: {
    data_source_id: number;
    sync_type: string;
  }): Promise<any> => {
    const response = await apiClient.post('/data/sync/create/', data);
    return response.data;
  },

  // 获取同步状态
  getSyncStatus: async (): Promise<any> => {
    const response = await apiClient.get('/data/sync/status/');
    return response.data;
  },

  // 获取下载进展
  getDownloadProgress: async (): Promise<any> => {
    const response = await apiClient.get('/data/download/progress/');
    return response.data;
  },

  // 下载基金列表
  downloadFundList: async (data: { fund_type: string }): Promise<any> => {
    const response = await apiClient.post('/data/update/fund_list/', data, {
      timeout: 60000 // 增加超时时间到60秒，因为下载大量基金数据需要更长时间
    });
    return response.data;
  },

  // 更新基金列表
  updateFundList: async (): Promise<any> => {
    const response = await apiClient.post('/data/update/fund-list/');
    return response.data;
  },

  // 更新基金详情
  updateFundDetail: async (): Promise<any> => {
    const response = await apiClient.post('/data/update/fund_detail/', {}, {
      timeout: 60000 // 增加超时时间到60秒
    });
    return response.data;
  },

  // 更新基金净值
  updateFundNav: async (): Promise<any> => {
    const response = await apiClient.post('/data/fund-nav-update/start/', {});
    return response.data;
  },

  // 下载基金基本信息
  downloadFundBasicInfo: async (data: any): Promise<any> => {
    const response = await apiClient.post('/data/download/fund-basic-info/', data);
    return response.data;
  },

  // 下载开放式基金信息
  downloadOpenFundInfo: async (data: any): Promise<any> => {
    const response = await apiClient.post('/data/download/open-fund-info/', data);
    return response.data;
  },

  // 下载基金详细信息
  downloadFundDetails: async (force: boolean = false): Promise<any> => {
    const response = await apiClient.post('/data/update/fund_detail/', {
      force: force
    }, {
      timeout: 120000 // 增加超时时间到120秒，因为下载详细信息需要更长时间
    });
    return response.data;
  },

  // 下载基金净值
  downloadFundNav: async (): Promise<any> => {
    const response = await apiClient.post('/data/download/fund-nav/', {}, {
      timeout: 120000 // 增加超时时间到120秒
    });
    return response.data;
  },

  // 同步基金数据
  syncFundData: async (data: { fund_codes: string[]; sync_net_value: boolean }): Promise<any> => {
    const response = await apiClient.post('/data/sync/fund-data/', data);
    return response.data;
  },

  // 获取最新净值
  getLatestNetValue: async (fundCodes: string): Promise<any> => {
    const response = await apiClient.get('/data/fund/net-value/latest/', {
      params: { fund_codes: fundCodes }
    });
    return response.data;
  },

  // 刷新净值
  refreshNetValue: async (fundCodes: string[]): Promise<any> => {
    const response = await apiClient.post('/data/sync/fund/net-value/', {
      fund_codes: fundCodes
    });
    return response.data;
  },

  // 通用更新数据
  updateData: async (dataType: string): Promise<any> => {
    const response = await apiClient.post(`/data/update/${dataType}/`);
    return response.data;
  },

  // 数据库检查和清理API
  checkDatabaseData: async (): Promise<any> => {
    const response = await apiClient.get('/data/check/database-data/');
    return response.data;
  },

  clearFundData: async (dataType: string): Promise<any> => {
    const response = await apiClient.delete('/data/clear/fund-data/', {
      data: { data_type: dataType }
    });
    return response.data;
  },

  // 停止下载任务
  stopDownloadTask: async (taskId: number): Promise<any> => {
    const response = await apiClient.post('/data/download/stop/', {
      task_id: taskId
    });
    return response.data;
  },

  // 停止基金详细信息下载
  stopFundDownload: async (): Promise<any> => {
    const response = await apiClient.post('/data/fund-download/stop/');
    return response.data;
  },

  // 获取基金下载状态
  getFundDownloadStatus: async (): Promise<any> => {
    const response = await apiClient.get('/data/fund-download/status/');
    return response.data;
  },

  // 获取已入库基金统计
  getStoredFundCount: async (): Promise<any> => {
    const response = await apiClient.get('/data/fund-detail/stored-count/');
    return response.data;
  },

  // 继续下载基金详细信息
  continueFundDetailDownload: async (): Promise<any> => {
    const response = await apiClient.post('/data/fund-detail/continue-download/');
    return response.data;
  },

  // 基金净值下载相关API
  startFundNavDownload: async (): Promise<any> => {
    const response = await apiClient.post('/data/fund-nav-download/start/');
    return response.data;
  },

  stopFundNavDownload: async (): Promise<any> => {
    const response = await apiClient.post('/data/fund-nav-download/stop/');
    return response.data;
  },

  continueFundNavDownload: async (): Promise<any> => {
    const response = await apiClient.post('/data/fund-nav-download/continue/');
    return response.data;
  },

  getFundNavDownloadStatus: async (): Promise<any> => {
    const response = await apiClient.get('/data/fund-nav-download/status/');
    return response.data;
  },

  getFundNavDownloadStatistics: async (): Promise<any> => {
    const response = await apiClient.get('/data/fund-nav-download/statistics/');
    return response.data;
  },

  resetFundNavDownload: async (): Promise<any> => {
    const response = await apiClient.post('/data/fund-nav-download/reset/');
    return response.data;
  },

  restartFundNavDownload: async (limit?: number): Promise<any> => {
    const response = await apiClient.post('/data/fund-nav-download/restart/', { limit });
    return response.data;
  },

  // 基金净值更新相关API
  startFundNavUpdate: async (): Promise<any> => {
    const response = await apiClient.post('/data/fund-nav-update/start/', {});
    return response.data;
  },

  stopFundNavUpdate: async (): Promise<any> => {
    const response = await apiClient.post('/data/fund-nav-update/stop/', {});
    return response.data;
  },

  getFundNavUpdateStatus: async (): Promise<any> => {
    const response = await apiClient.get('/data/fund-nav-update/status/');
    return response.data;
  },

  getFundNavUpdateStatistics: async (): Promise<any> => {
    const response = await apiClient.get('/data/fund-nav-update/statistics/');
    return response.data;
  },

  // 基金历史净值明细相关API
  getFundNavDetail: async (params?: {
    fund_codes?: string;
    page?: number;
    page_size?: number;
  }): Promise<PaginatedResponse<any>> => {
    const response = await apiClient.get('/data/fund-nav-detail/', { params });
    return response.data;
  },

  getFundNavDetailHistory: async (fundCode: string, params?: {
    start_date?: string;
    end_date?: string;
    period?: string;
    page?: number;
    page_size?: number;
  }): Promise<any> => {
    const response = await apiClient.get(`/data/fund-nav-detail/${fundCode}/history/`, { params });
    return response.data;
  },

  // 基金详情页面相关API
  getFundListForSelect: async (): Promise<{ code: string; name: string }[]> => {
    const response = await apiClient.get('/data/funds/list-for-select/');
    // Handle the response structure: { status: 'success', data: [...], count: number }
    if (response.data && response.data.status === 'success' && response.data.data) {
      return response.data.data.map((item: any) => ({
        code: item.fund_code,
        name: item.fund_name
      }));
    }
    return [];
  },

  getFundDetailInfo: async (fundCode: string): Promise<any> => {
    const response = await apiClient.get(`/data/funds/${fundCode}/detail-info/`);
    return response.data;
  },

  getFundNavHistoryChart: async (fundCode: string): Promise<any> => {
    const response = await apiClient.get(`/data/funds/${fundCode}/nav-history-chart/`);
    return response.data;
  },
};

export default apiClient;